//
//  PhotoSelectController.swift
//  图片选择器
//
//  Created by 庄猛 on 17/1/16.
//  Copyright © 2017年 BeiSheng. All rights reserved.
//

import UIKit
import Photos
//import AssetsLibrary
import ZLPhotoBrowser

/// cell之间的间隙
private let photoCellMargin : CGFloat = 10

/// cell最大列数
private let photoCellMaxCol : CGFloat = 3


class PhotoSelectController: UICollectionViewController {

    lazy var images = [UIImage]()
    
//    var lastSelectAssets = [PHAsset]()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.viewBgGrey()

        self.collectionView!.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: PhotoCollectionViewCell.identifer())

    }


    init(){
    super.init(collectionViewLayout: PhotoFlowLayout())

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




}


extension PhotoSelectController{

    override func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return images.count + 1
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCollectionViewCell.identifer(), for: indexPath) as! PhotoCollectionViewCell

        cell.delegate = self

        cell.image = (indexPath.item < images.count) ? images[indexPath.item] : nil

        cell.index = indexPath

        return cell
    }

}


extension PhotoSelectController:PhotoCellDelegate{

    func addBtnDidClick(index: IndexPath){
        
        
        let ation = ZLPhotoActionSheet()
        ation.sortAscending = true
        ation.allowSelectImage = true
        ation.allowSelectGif = false
        ation.allowSelectVideo = false
        ation.allowSelectLivePhoto = false
        ation.allowForceTouch = false
        ation.allowEditImage = true
        ation.allowTakePhotoInLibrary = true
        
        ation.maxSelectCount = 1
        ation.maxPreviewCount = 20
        ation.sender = self
        
        ation.selectImageBlock = {[weak self] (images,phassets,isOk) -> () in
            
            self?.images = images
            
            self?.collectionView?.reloadData()
            
        }
        
        ation.showPhotoLibrary()
//        ation.showPreview(animated: true)
        
        
            }

//        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
//          return
//
//        }
//
//
//
//        let pickerVC = UIImagePickerController()
//        pickerVC.sourceType = .photoLibrary
//        pickerVC.delegate = self
//
//
//        present(pickerVC, animated: true, completion: nil)


//    }

    func deleBtnDidClick(index: IndexPath){

        images.remove(at: index.item)


        collectionView?.reloadData()


    }
    
}



extension PhotoSelectController:UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        guard let image = info[UIImagePickerControllerOriginalImage]  as? UIImage else {
            return
        }

        guard let url = info[UIImagePickerControllerReferenceURL] as? URL else {
            
            return
        }
        
        
        QL1(url)

//        let photo = PHPhotoLibrary.shared()

        

    

//        let assets = ALAssetsLibrary()
//        assets.asset(for: url, resultBlock: { (asset) in
//
//            let imageRef = asset?.defaultRepresentation().fullResolutionImage()
//
//            let cgImage = imageRef?.takeUnretainedValue()
//
//            let image = UIImage(cgImage: cgImage!)
//
//
//            QL1(image)
//
//        }) { (error) in
//
//        }

//        QL1(info)


        let newImage = scaleImage(image, width: image.size.width, height: image.size.height)


        images.append(newImage)
        
        
        collectionView?.reloadData()

        picker.dismiss(animated: true, completion: nil)

    }



    fileprivate func scaleImage(_ image: UIImage, width: CGFloat, height: CGFloat) -> UIImage {


        let temp = height/width * 200

        UIGraphicsBeginImageContext(CGSize(width: 200, height: temp))

        image.draw(in: CGRect(x: 0, y: 0, width: 200, height: temp))


        return   UIGraphicsGetImageFromCurrentImageContext()!

    }
    
    
    
    
    
    
    
}




protocol PhotoCellDelegate :NSObjectProtocol{
    func addBtnDidClick(index: IndexPath)

    func deleBtnDidClick(index: IndexPath)

}

class PhotoCollectionViewCell: UICollectionViewCell {


    var index : IndexPath?


    weak var delegate : PhotoCellDelegate?

    var image: UIImage? {

        didSet{

            if image != nil {

               iconBtn.setBackgroundImage(nil, for: .normal)
                iconBtn.setBackgroundImage(nil, for: .highlighted)
                iconBtn.setImage(image, for: .normal)
                iconBtn.setImage(image, for: .highlighted)

                colseBtn.isHidden = false

            } else {


                iconBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), for: .normal)
                iconBtn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), for: .highlighted)
                iconBtn.setImage(nil, for: .normal)
                iconBtn.setImage(nil, for: .highlighted)

                colseBtn.isHidden = true

            }




        }




    }

    fileprivate lazy var iconBtn:UIButton = {
      let temp = UIButton()

        temp.setBackgroundImage(UIImage(named: "compose_pic_add"), for: .normal)
        temp.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), for: .highlighted)
        
        temp.imageView?.contentMode = .scaleAspectFill

        temp.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)

        return temp
    }()


    fileprivate lazy var colseBtn:UIButton = {
        let temp = UIButton()

        temp.addTarget(self, action: #selector(deleBtnDidClick), for: .touchUpInside)

//        temp.setBackgroundImage(UIImage(named: "compose_photo_close"), for: .normal)

        temp.setImage(UIImage(named: "compose_photo_close"), for: .normal)

        temp.backgroundColor = UIColor.red

        temp.isHidden = true

        temp.backgroundColor = UIColor.clear

        temp.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 10, 0)
//        temp.sizeToFit()



        return temp
    }()



    @objc private func addBtnDidClick(){

        if colseBtn.isHidden == true {

            delegate?.addBtnDidClick(index: index!)

        }



    }
    


    @objc private func deleBtnDidClick(){

     delegate?.deleBtnDidClick(index: index!)
        
        
    }







    override init(frame: CGRect) {
        super.init(frame: frame)

        contentView.addSubview(iconBtn)

        contentView.addSubview(colseBtn)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func layoutSubviews() {

        super.layoutSubviews()

        iconBtn.frame = bounds


        colseBtn.frame = CGRect(x: bounds.size.width - 35, y: 0, width: 35, height: 35)

    }




    class func identifer() -> String{

        return NSStringFromClass(self)
        
    }


}




class PhotoFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {

        super.prepare()

        let itemW = (UIScreen.main.bounds.size.width - (photoCellMaxCol + 1) * photoCellMargin) / photoCellMaxCol

        itemSize = CGSize(width: itemW, height: itemW)

        minimumLineSpacing = photoCellMargin
        minimumInteritemSpacing = photoCellMargin
        collectionView?.showsVerticalScrollIndicator = false


        collectionView?.contentInset = UIEdgeInsetsMake(photoCellMargin, photoCellMargin, photoCellMargin, photoCellMargin)


    }
}
